package com.wgke.bluetooth.ui;

import android.Manifest;
import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.app.ActivityCompat;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.core.view.WindowInsetsControllerCompat;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import com.wgke.bluetooth.R;
import com.wgke.bluetooth.utils.ToastUtil;
import com.wgke.bluetooth.vm.BaseVM;

import org.greenrobot.eventbus.EventBus;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

public abstract class BaseActivity<VM extends BaseVM> extends AppCompatActivity {

    public boolean isOpenBluetooth = false;
    private BluetoothStateReceiver bluetoothStateReceiver;
    private Handler handler = new Handler(Looper.getMainLooper());
    public boolean openBluetoothReceiver = false;

    protected VM vm;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(layoutId());
        vm = createViewModel();
        initView();
        vm.isFinishPage.observe(this, aBoolean -> {
            if (aBoolean) finish();
        });
        requestPermissions(0);
        if (openBluetoothReceiver) {
            // 初始化广播接收器
            bluetoothStateReceiver = new BluetoothStateReceiver();
            // 注册接收器
            IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
            registerReceiver(bluetoothStateReceiver, filter);
        }
        initStateBar();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (bluetoothStateReceiver != null) {
            unregisterReceiver(bluetoothStateReceiver);
        }
    }

    protected VM createViewModel() {
        return new ViewModelProvider(this).get(providerVMClass());
    }

    @SuppressWarnings("unchecked")
    private Class<VM> providerVMClass() {
        try {
            // 获取带有泛型信息的父类类型
            ParameterizedType parameterizedType = (ParameterizedType) getClass().getGenericSuperclass();
            Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
            if (actualTypeArguments.length > 0) {
                // 获取第一个类型参数（VM的类型）
                return (Class<VM>) actualTypeArguments[0];
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        throw new IllegalStateException("Unable to determine generic VM class");
    }

    public abstract int layoutId();

    public abstract void initView();

    public void requestPermissions(int count) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            Log.e("BaseActivity", "requestPermissions:" + count);
            if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                if (count < 1) {
                    requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.BLUETOOTH_CONNECT, Manifest.permission.BLUETOOTH_SCAN}, 1);
                } else {
                    postDelayed(1000, () -> finish());
                    ToastUtil.showLongMsg("请手动开启定位权限");
                }
            } else {
                nextStep(1);
            }
        }
    }


    public void requestPermissions2(int count) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            Log.e("BaseActivity", "requestPermissions2:" + count);
            if (checkSelfPermission(Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED || checkSelfPermission(Manifest.permission.BLUETOOTH_SCAN) != PackageManager.PERMISSION_GRANTED) {
                if (count < 1) {
                    requestPermissions(new String[]{Manifest.permission.BLUETOOTH_CONNECT, Manifest.permission.BLUETOOTH_SCAN}, 3);
                } else {
                    Toast.makeText(this, "我们需要定位权限用于蓝牙设备扫描,需要你手动赋权", Toast.LENGTH_SHORT).show();
                }
            } else {
                nextStep(2);
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        Log.e("BaseActivity", "onRequestPermissionsResult:" + requestCode);
        if (requestCode == 1) {
            postDelayed(1000, () -> requestPermissions(1));
        } else if (requestCode == 2) {
            requestPermissions2(1);
        } else if (requestCode == 3) {
            requestPermissions2(1);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 3) {
            nextStep(2);
        }
    }

    @SuppressLint("MissingPermission")
    public boolean isOpenBluetooth(BluetoothAdapter bluetoothAdapter) {
        if (!bluetoothAdapter.isEnabled()) {
            ToastUtil.showMsg("请先打开蓝牙");
            if (!bluetoothAdapter.isEnabled()) {
                Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                startActivityForResult(enableBtIntent, 3);
            }
            return false;
        }
        return true;
    }


    public void nextStep(int i) {

    }

    public void postDelayed(long delayMillis, Runnable r) {
        handler.postDelayed(r, delayMillis);
    }

    public class BluetoothStateReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            final String action = intent.getAction();

            if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
                final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR);
                isOpenBluetooth = false;
                switch (state) {
                    case BluetoothAdapter.STATE_OFF:
                        // 蓝牙已关闭
                        Log.d("BluetoothState", "蓝牙已关闭");
                        break;
                    case BluetoothAdapter.STATE_TURNING_OFF:
                        // 蓝牙正在关闭
                        Log.d("BluetoothState", "蓝牙正在关闭");
                        break;
                    case BluetoothAdapter.STATE_ON:
                        isOpenBluetooth = true;
                        // 蓝牙已开启
                        Log.d("BluetoothState", "蓝牙已开启");
                        break;
                    case BluetoothAdapter.STATE_TURNING_ON:
                        // 蓝牙正在开启
                        Log.d("BluetoothState", "蓝牙正在开启");
                        break;
                }
            }
        }
    }

    public boolean isUseEventBus() {
        return true;
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (isUseEventBus()) {
            EventBus.getDefault().register(this);
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (isUseEventBus()) {
            EventBus.getDefault().unregister(this);
        }
    }

    protected void initStateBar() {
        Toolbar toolbar = findViewById(R.id.toolbar);
        if (toolbar != null) {

            setSupportActionBar(toolbar);
            // 处理系统栏插入
            ViewCompat.setOnApplyWindowInsetsListener(toolbar, (v, insets) -> {
                int statusBarHeight = insets.getInsets(WindowInsetsCompat.Type.systemBars()).top;
                v.setPadding(0, statusBarHeight, 0, 0);
                ViewGroup.LayoutParams params = v.getLayoutParams();
                params.height = getResources().getDimensionPixelSize(R.dimen.action_bar_size) + statusBarHeight;
                v.setLayoutParams(params);
                return insets;
            });

            // 设置状态栏图标颜色
            WindowInsetsControllerCompat controller = new WindowInsetsControllerCompat(getWindow(), getWindow().getDecorView());
            boolean isDark = (getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK) == Configuration.UI_MODE_NIGHT_YES;
            controller.setAppearanceLightStatusBars(!isDark);

            toolbar.setNavigationOnClickListener(v -> finish());
        }
    }
}
